// import ethers.js
// 通过ethers部署合约

// create main function

// execute main finction

const { ethers } = require("hardhat")

async function main() {
    //create factory
    const fundMeFactory = await ethers.getContractFactory("FundMe");
    console.log("contract deploying")
    // deploy contract from factory
    const fundMe = await fundMeFactory.deploy(10);
    await fundMe.waitForDeployment()
    console.log(`contract has been deployed successfally, contract address is  ${fundMe.target}`)

    // verify fundme
    if (hre.network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY) {
        console.log("Waiting for 5 confirmations")
        await fundMe.deploymentTransaction().wait(3)
        await verify(fundMe.target, [10])
    } else {
        console.log("verification skipped..")
    }

    console.log("fund the contract...")
    // init 2 accounts
    // const [firstAccount, secondAccount] = await ethers.getSigners();
    // console.log("first account address is ", firstAccount.address)
    // console.log("second account address is ", secondAccount.address)

    // fund contract with first account
    const fundTx = await fundMe.fund(
        { value: ethers.parseEther("0.1") }
    )
    await fundTx.wait()

    console.log("funded the contract")

    // check balance of contract
    const fundMeBalance = await ethers.provider.getBalance(fundMe.target)
    console.log(`Balance of the contract is ${fundMeBalance}`)

    const [firstAccount, secondAccount] = await ethers.getSigners();
    console.log(`first account address is ${firstAccount.address}`)
    console.log(`second account address is ${secondAccount.address}`)

    console.log("fetching the funds of the first account...")
    const fundsOfFirstAccount = await fundMe.listOfFunders(firstAccount.address)
    console.log(`Current funds of first account is ${fundsOfFirstAccount}`)

    console.log("fund the contract on behaif of the second addcount...")
    const secondFundTx = await fundMe.connect(secondAccount).fund({
        value: ethers.parseEther("0.1")
    })
    await secondFundTx.wait()

    console.log("fetching the funds of the second account...")
    const fundsOfSecondAccount = await fundMe.listOfFunders(secondAccount.address)
    console.log(`Current funds of second addount is ${fundsOfSecondAccount}`)

}

async function verify(fundMeAddr, args) {

    await hre.run("verify:verify", {
        address: fundMeAddr,
        constructorArguments: [args],
    });
}


main().then().catch((error) => {
    console.error(error)
    process.exit(1)
})

